package com.aaa.service;
import com.aaa.entity.Menu;
import com.aaa.entity.User;
import com.aaa.fegin.MenuFeign;
import com.aaa.fegin.UserFeign;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MyUserService implements UserDetailsService {
    @Resource
    private UserFeign userFeign;
    @Resource
    private MenuFeign menuFeign;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userFeign.getByUsername(username);
        System.out.println("user===== = " + user);
        if(user==null){
            throw new RuntimeException("账号不存在");
        }
        //查询该用户具有的权限。
        List<Menu> menuList = menuFeign.findByUserid(user.getUserId());
        System.out.println("该用户具有的权限=============== " + menuList);
        Collection<SimpleGrantedAuthority> authorities=menuList.stream().map(item->new SimpleGrantedAuthority(item.getPercode())).collect(Collectors.toList());
        return  new org.springframework.security.core.userdetails.User(user.getPhone(),user.getPassword(),authorities);
    }




}
